<template>
  <div class="app-container">
    <div class="p-5">
      <el-card shadow="never">
        <el-row justify="space-around">
          <el-col :span="4" :xs="24">
            <div class="flex h-full items-center">
              <img class="w-20 h-20 mr-5 rounded-full" :src="avatar" />
              <div>
                <p>{{ greetings }}</p>
              </div>
            </div>
          </el-col>
          <el-col :span="13" :xs="24">
            <div class="carousel-container">
              <el-carousel height="auto" autoplay>
                <el-carousel-item v-for="item in bannerList" :key="item.id" style="height: 400px">
                  <img :src="item.src" :alt="item.title" />
                </el-carousel-item>
              </el-carousel>
            </div>
          </el-col>
          <el-col :span="4" :xs="24">
            <p class="text-sm text-gray">今天是 {{ weatherInfo?.time }}</p>
            <p class="text-sm text-gray">
              {{ weatherInfo?.province }}
              {{ weatherInfo?.city }}
              今日天气
              <span v-text="getWeatherDescription(weatherInfo?.weatherCode || 0)"></span>
            </p>
            <p class="text-sm text-gray">
              气温 {{ weatherInfo?.temperature2mMin }} ℃ ~{{ weatherInfo?.temperature2mMax }}℃
            </p>
            <p class="text-sm text-gray">
              体感温度 {{ weatherInfo?.apparentTemperatureMin }} ℃ ~{{
                weatherInfo?.apparentTemperatureMax
              }}℃
            </p>
            <p class="text-sm text-gray">日出 {{ weatherInfo?.sunrise }}</p>
            <p class="text-sm text-gray">日落 {{ weatherInfo?.sunset }}</p>
            <p class="text-sm text-gray">
              紫外线指数 {{ weatherInfo?.uvIndexMax }}
              <span v-if="(weatherInfo?.uvIndexMax || 0) >= 8">紫外线很强，注意做好防晒</span>
            </p>
          </el-col>
        </el-row>
      </el-card>
      <el-card shadow="always" style="margin-top: 20px">
        <el-row>
          <el-col :span="2"><div class="title">推荐岗位</div></el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-card shadow="never">
              <div class="card-container">
                <div class="card-container__item">关键字</div>
                <div class="card-container" style="width: 500px">
                  <el-input v-model="queryParams.keywords" placeholder="请输入搜索关键字" />
                  <el-button type="success" @click="handleQuery">
                    <el-icon><Search /></el-icon>
                    搜索
                  </el-button>
                  <el-button type="primary" @click="handleResetQuery">
                    <el-icon><SwitchButton /></el-icon>
                    重置
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-card shadow="never">
              <div class="card-container">
                <div class="card-container__item">行业类型:</div>
                <button
                  v-for="(type, index) in types.JOB_TYPE"
                  :key="type.itemValue"
                  :class="['card-container_button-item', { 'active-item': type.active }]"
                  class="card-container_button-item"
                  @click="handleClickItem(type, index)"
                >
                  {{ type.itemDesc }}
                </button>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-card shadow="never">
              <div class="card-container">
                <div class="card-container__item">学历要求:</div>
                <button
                  v-for="(type, index) in types.EDUCATIONAL"
                  :key="type.itemValue"
                  :class="['card-container_button-item', { 'active-item': type.active }]"
                  class="card-container_button-item"
                  @click="handleClickItem(type, index)"
                >
                  {{ type.itemDesc }}
                </button>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-card shadow="never">
              <div class="card-container">
                <div class="card-container__item">结算方式:</div>
                <button
                  v-for="(type, index) in types.SETTLEMENT"
                  :key="type.itemValue"
                  :class="['card-container_button-item', { 'active-item': type.active }]"
                  class="card-container_button-item"
                  @click="handleClickItem(type, index)"
                >
                  {{ type.itemDesc }}
                </button>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <el-row v-infinite-scroll="handleNextPage" justify="center">
          <el-col :span="24">
            <div v-if="!gridLoading && dataList.length == 0" class="no-data">暂无数据...</div>
            <div class="grid-container">
              <div class="content">
                <div class="product-grid">
                  <div v-for="data in dataList" class="product-card">
                    <div class="product-info">
                      <h3>{{ data.title }}</h3>
                      <h5>{{ data.name }}</h5>
                      <div class="dict-container">
                        <DictLabel v-model="data.type" code="JOB_TYPE" />
                        <DictLabel v-model="data.educational" code="EDUCATIONAL" />
                        <DictLabel v-model="data.settlement" code="SETTLEMENT" />
                      </div>
                      <div class="product-image">
                        <QuillViewer v-model="data.description" />
                        <div class="quick-view" @click="showDetails(data)">查看详情</div>
                      </div>
                      <div class="time-section">
                        <span class="time">{{ data.workTime }}</span>
                        <span class="time">{{ data.workHours }}</span>
                      </div>
                      <div class="price-section">
                        <span class="price">{{ data.hourlyWage }}</span>
                      </div>
                      <router-link :to="`/center/sendApplication?id=${data.id}`">
                        <button v-if="userStore.userInfo.userId" class="add-to-cart">
                          <el-icon><Promotion /></el-icon>
                          投递简历
                        </button>
                      </router-link>
                    </div>
                  </div>
                  <div v-for="item in loadCount" v-if="gridLoading" class="product-card">
                    <div class="product-info">
                      <el-skeleton
                        :loading="gridLoading"
                        animated
                        :throttle="{ leading: 500, trailing: 500, initVal: true }"
                      >
                        <template #template>
                          <el-skeleton-item variant="h1" style="width: 80%" />
                          <el-skeleton-item variant="h3" style="width: 40%" />
                          <el-skeleton-item
                            variant="image"
                            style="width: 200px; height: 265px; margin: 0 20px"
                          />
                          <div>
                            <el-row>
                              <el-col :span="12">
                                <el-skeleton-item variant="h3" style="width: 80%" />
                              </el-col>
                              <el-col :span="12">
                                <el-skeleton-item variant="h3" style="width: 80%" />
                              </el-col>
                              <el-col :span="16"></el-col>
                              <el-col :span="8">
                                <el-skeleton-item variant="text" style="width: 60%" />
                              </el-col>
                            </el-row>
                          </div>
                        </template>
                      </el-skeleton>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <el-dialog
      v-model="infoDialog.visible"
      :title="infoDialog.title"
      width="900px"
      @close="handleCloseView"
    >
      <el-form v-loading="infoLoad">
        <el-row>
          <el-col :span="24">
            <el-form-item label="岗位标题:" prop="title">
              {{ jobInfo.title }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="岗位名称:" prop="name">
              {{ jobInfo.name }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="行业类型:" prop="type">
              <DictLabel v-model="jobInfo.type" code="JOB_TYPE" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="薪资范围:" prop="hourlyWage">
              {{ jobInfo.hourlyWage }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="结算方式:" prop="settlement">
              <DictLabel v-model="jobInfo.settlement" code="SETTLEMENT" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="学历要求:" prop="educational">
              <DictLabel v-model="jobInfo.educational" code="EDUCATIONAL" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="岗位描述:" prop="description">
              <QuillViewer v-model="jobInfo.description" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="工作时间:" prop="workTime">
              {{ jobInfo.workTime }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工作时段:" prop="workHours">
              {{ jobInfo.workHours }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="工作要求:" prop="jobRequirements">
              <QuillViewer v-model="jobInfo.jobRequirements" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="工作地点:" prop="workLocation">
              {{ jobInfo.workLocation }}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="福利待遇:" prop="welfare">
              {{ jobInfo.welfare }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-if="jobInfo.publishTime" :span="6">
            <el-form-item label="发布时间:" prop="welfare">
              {{ jobInfo.publishTime }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseView">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import homeImage from "@/assets/images/home.jpg";
defineOptions({
  name: "Dashboard",
  inheritAttrs: false,
});
import WeatherApi, { type WeatherInfo } from "@/api/system/weather.api";
import DictAPI, { type DictItemOption } from "@/api/system/dict.api";
import JobApi, { JobVO, type JobPageQuery } from "@/api/job/job.api";

import QuillViewer from "@/components/QuillEditor/viewer.vue";
import DictLabel from "@/components/Dict/DictLabel.vue";

import Banner1 from "@/assets/images/banner/banner-1.jpg";
import Banner2 from "@/assets/images/banner/banner-2.jpg";
import Banner3 from "@/assets/images/banner/banner-3.jpg";
import Banner4 from "@/assets/images/banner/banner-4.jpg";
import { ResumeVo } from "@/api/resume/resume.api";

import { useUserStore } from "@/store";
import router from "@/router";
const weatherInfo = ref<WeatherInfo>();
const avatar = ref("");
const userStore = useUserStore();

const types = reactive({
  JOB_TYPE: Array<DictItemOption>(),
  EDUCATIONAL: Array<DictItemOption>(),
  SETTLEMENT: Array<DictItemOption>(),
});
const activeType = reactive({
  JOB_TYPE: Array<DictItemOption>(),
  EDUCATIONAL: Array<DictItemOption>(),
  SETTLEMENT: Array<DictItemOption>(),
});

const dataList = ref<Array<JobVO>>([]);

const gridLoading = ref(false);
const queryParams = ref<JobPageQuery>({
  keywords: "",
  typeList: [],
  settlementList: [],
  educationalList: [],
  total: 5,
  pageNum: 1,
  pageSize: 10,
});
const loadCount = ref(queryParams.value.total);
const jobInfo = reactive<JobVO>({});
const infoDialog = reactive({
  title: "",
  visible: false,
});
const infoLoad = ref(false);

const bannerList = [
  { id: 1, src: Banner1, title: "这是一个轮播图" },
  { id: 2, src: Banner2, title: "这是一个轮播图" },
  { id: 3, src: Banner3, title: "这是一个轮播图" },
  { id: 4, src: Banner4, title: "这是一个轮播图" },
];

onMounted(async () => {
  WeatherApi.getInfo().then((data) => {
    weatherInfo.value = data;
  });
  avatar.value = homeImage;

  DictAPI.getDictItems("JOB_TYPE").then((data) => {
    types.JOB_TYPE = data;
  });
  DictAPI.getDictItems("SETTLEMENT").then((data) => {
    types.SETTLEMENT = data;
  });
  DictAPI.getDictItems("EDUCATIONAL").then((data) => {
    types.EDUCATIONAL = data;
  });
  handleQuery();
});

function handleNextPage() {
  const { pageSize, pageNum, total } = queryParams.value;
  if (total && total > pageNum * pageSize && !gridLoading.value) {
    queryParams.value.pageNum = pageNum + 1;
    gridLoading.value = true;
    const remain = total - pageNum * pageSize;
    loadCount.value = remain > pageNum * pageSize ? pageSize : remain;
    handleScroll();
  }
}

function handleResetQuery() {
  queryParams.value.pageNum = 1;
  queryParams.value.keywords = undefined;
  activeType.JOB_TYPE = [];
  activeType.SETTLEMENT = [];
  activeType.EDUCATIONAL = [];
  types.JOB_TYPE.map((item) => {
    item.active = false;
  });
  types.SETTLEMENT.map((item) => {
    item.active = false;
  });
  types.EDUCATIONAL.map((item) => {
    item.active = false;
  });

  handleQuery();
}
function handleQuery() {
  gridLoading.value = true;
  queryParams.value.pageNum = 1;
  loadCount.value = 5;
  dataList.value = [];
  queryParams.value.typeList = activeType.JOB_TYPE.map((obj) => obj.itemValue);
  queryParams.value.settlementList = activeType.SETTLEMENT.map((obj) => obj.itemValue);
  queryParams.value.educationalList = activeType.EDUCATIONAL.map((obj) => obj.itemValue);
  setTimeout(() => {
    JobApi.publicJob(queryParams.value)
      .then((data) => {
        dataList.value = data.records;
        queryParams.value.total = data.total;
      })
      .finally(() => {
        gridLoading.value = false;
      });
  }, 300);
}

function handleScroll() {
  gridLoading.value = true;
  JobApi.publicJob(queryParams.value)
    .then((data) => {
      dataList.value = [...dataList.value, ...data.records];
      queryParams.value.total = data.total;
    })
    .finally(() => {
      gridLoading.value = false;
    });
}
function sendResume(data: ResumeVo) {
  if (userStore.userInfo.userId) {
    router.push(`/center/sendApplication?id=${data.id}`);
  } else {
    ElMessage.error("请先登录");
  }
}

function showDetails(data: ResumeVo) {
  if (userStore.userInfo.userId) {
    infoDialog.visible = true;
    infoDialog.title = "岗位信息";
    infoLoad.value = true;
    JobApi.getById(data.id).then((data) => {
      infoLoad.value = false;
      Object.assign(jobInfo, data);
    });
  } else {
    ElMessage.error("请先登录");
  }
}

function handleCloseView() {
  infoDialog.visible = false;
}
function handleClickItem(item: DictItemOption, index: number) {
  switch (item.dictCode) {
    case "JOB_TYPE": {
      const active = !types.JOB_TYPE[index].active;
      types.JOB_TYPE[index].active = active;
      if (active) {
        activeType.JOB_TYPE.push(types.JOB_TYPE[index]);
      } else {
        activeType.JOB_TYPE = activeType.JOB_TYPE.filter(
          (type) => type.itemValue !== item.itemValue
        );
      }
      break;
    }
    case "SETTLEMENT": {
      const active = !types.SETTLEMENT[index].active;
      types.SETTLEMENT[index].active = active;
      if (active) {
        activeType.SETTLEMENT.push(types.SETTLEMENT[index]);
      } else {
        activeType.SETTLEMENT = activeType.SETTLEMENT.filter(
          (type) => type.itemValue !== item.itemValue
        );
      }
      break;
    }
    case "EDUCATIONAL": {
      const active = !types.EDUCATIONAL[index].active;
      types.EDUCATIONAL[index].active = active;
      if (active) {
        activeType.EDUCATIONAL.push(types.EDUCATIONAL[index]);
      } else {
        activeType.EDUCATIONAL = activeType.EDUCATIONAL.filter(
          (type) => type.itemValue !== item.itemValue
        );
      }
      break;
    }
  }
  handleQuery();
}
const date: Date = new Date();
const greetings = computed(() => {
  const hours = date.getHours();
  if (hours >= 6 && hours < 8) {
    return "晨起披衣出草堂，轩窗已自喜微凉🌅！";
  } else if (hours >= 8 && hours < 12) {
    return "晨曦正踮着脚尖路过你的窗台🌿. 出发吧，今日的冒险要蘸着阳光书写🦋🐿️✨";
  } else if (hours >= 12 && hours < 18) {
    return "太阳在青瓷碗沿打盹儿，我往你的柠檬茶里投了粒会游动的光斑。所有昏昏欲睡的故事忽然踮脚起舞，而你的名字被蝉翼驮着，正轻轻——跌进我写满草莓籽与彩虹糖的纸飞机✈️🍉✨";
  } else if (hours >= 18 && hours < 24) {
    return "云絮正偷抿晚霞的胭脂🌆归鸟衔着余温掠过钟楼，风在窗棂摊开发烫的诗集——“白昼欠你的那捧星芒，此刻正叮咚沉入月亮的银盏。”";
  } else {
    return "偷偷向银河要了一把碎星，只等你闭上眼睛撒入你的梦中，晚安🌛！";
  }
});

function getWeatherDescription(code: number): string {
  switch (code) {
    case 0:
    case 1:
      return "晴";
    case 2:
    case 3:
      return "多云";
    case 45:
      return "雾";
    case 48:
      return "浓雾";
    case 51:
    case 53:
    case 55:
      return "小雨";
    case 56:
    case 57:
    case 66:
    case 67:
      return "冻雨";
    case 61:
    case 63:
    case 65:
      return "中雨";
    case 71:
    case 73:
    case 75:
      return "雪";
    case 77:
      return "冰雹";
    case 80:
    case 81:
    case 82:
      return "暴雨";
    case 85:
    case 86:
      return "大雪";
    case 95:
    case 96:
      return "雷阵雨";
    case 99:
      return "雷阵雨，伴有强降水";
    default:
      return "晴";
  }
}
</script>

<style lang="scss" scoped>
.carousel-container img {
  height: 100%;
  width: 80%;
}
.el-carousel__item {
  display: flex;
  justify-content: space-around;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}

.title {
  border-left: 3px solid #e69500;
  padding: 5px;
  margin: 10px 0;
}

.card-container {
  display: flex;
  justify-content: flex-start;

  &__item {
    padding: 5px;
  }
  &__item.gray {
    background-color: gray;
    color: white;
  }

  & > * {
    margin-right: 20px;
  }
  &_button-item {
    cursor: pointer;
    padding: 10px;
    background-color: #e0e0e0;
  }
  &_button-item.active-item {
    color: white;
    background-color: #f9aa33;
  }
  button:hover {
    color: white;
    background-color: #e74c3c;
  }
}

.grid-container {
  padding: 0 100px;
  .content {
    gap: 10px;
    overflow-y: hidden;
    overflow-x: auto;
    margin-top: 10px;
    padding: 10px;
  }
}

.filters button {
  padding: 8px 20px;
  border: none;
  background-color: #f0f0f0;
  color: #555;
  cursor: pointer;
  font-size: 0.9rem;
  white-space: nowrap;
  transition: all 0.3s;
}

.filters button:hover {
  background-color: #e0e0e0;
}

.filters button.active {
  background-color: #f9aa33;
  color: white;
  font-weight: 500;
}
/* 商品网格样式 */
.page-title {
  margin: 30px 0;
  font-size: 2rem;
  color: #4a6572;
  text-align: center;
}

.no-data {
  margin: 0 auto;
  margin: 20px;
  text-align: center;
}
.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 25px;
  margin-bottom: 50px;

  .el-skeleton {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
    gap: 25px;
  }
}

/* 商品卡片样式 */
.product-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
  transition:
    transform 0.3s,
    box-shadow 0.3s;
}

.product-card:hover {
  transform: translateY(-10px);
  box-shadow: 0 12px 20px rgba(0, 0, 0, 0.15);
}
.dict-container {
  display: flex;
  justify-content: space-around;
}
.product-image {
  position: relative;
  height: 200px;
  overflow: hidden;
  cursor: pointer;
}

.quick-view {
  position: absolute;
  bottom: -50px;
  left: 0;
  width: 100%;
  background-color: rgba(74, 101, 114, 0.85);
  color: white;
  text-align: center;
  padding: 10px;
  cursor: pointer;
  transition: bottom 0.3s;
}

.product-card:hover .quick-view {
  bottom: 0;
}

.product-info {
  padding: 20px;
}

.product-info h3 {
  font-size: 1.2rem;
  margin-bottom: 8px;
  color: #344955;
}

.description {
  color: #777;
  font-size: 0.9rem;
  margin-bottom: 15px;
  height: 40px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.time-section,
.price-section {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
  justify-content: space-around;
}

.price-section {
  justify-content: right;
  .price {
    color: red;
  }
}

.time {
  font-size: 1.3rem;
  font-weight: 650;
  color: #4a6572;
}

.add-to-cart {
  width: 100%;
  padding: 10px;
  background-color: #f9aa33;
  color: white;
  border: none;
  border-radius: 5px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.add-to-cart:hover {
  background-color: #e69500;
}
</style>
